package com.lz.library.base

import androidx.annotation.CallSuper
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.lz.library.R
import com.lz.library.extension.showToast
import com.lz.library.net.NetworkManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext

/**
 *  author: you : 2020/4/24
 *  在协程中,viewModelScope = CloseableCoroutineScope实现了Closeable,在onClear时自动关闭
 */
open class BaseViewModel<M : BaseModel>(protected val model: M? = null) : ViewModel(), DefaultLifecycleObserver {

    //View层的状态 指定ViewStatus中
    val viewStatus = SingleLiveData(ViewStatus.LOADING)

    //进度弹窗
    val dialogEvent = SingleLiveData<Boolean>()

    //activity finish
    val finishEvent = SingleLiveData<Boolean>()

    @CallSuper
    override fun onCleared() {
        model?.onCleared()
    }

    protected fun updateStatus(@ViewStatus status: Int) {
        viewStatus.setValue(status)
    }

    protected fun updateDialogLoading(showing: Boolean) {
        dialogEvent.setValue(showing)
    }

    fun finish() {
        finishEvent.setValue(true)
    }

    protected fun launch(
        scope: CoroutineScope = viewModelScope,
        context: CoroutineContext = EmptyCoroutineContext,
        start: CoroutineStart = CoroutineStart.DEFAULT,
        block: suspend CoroutineScope.() -> Unit
    ): Job = scope.launch(context, start, block)

    protected fun isNetworkConnected(showToast: Boolean = false): Boolean =
        NetworkManager.isNetworkConnected().also { if (!it && showToast) R.string.lib_networkError.showToast() }

}